import MysInfo from '../genshin/model/mys/mysInfo.js'
import puppeteer from '../../lib/puppeteer/puppeteer.js'
import fetch from 'node-fetch'
import fs from 'fs'

export class GenshinInventory extends plugin {
    constructor() {
        super({
            name: 'genshin-inventory',
            dsc: '原神背包查询',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^#原神背包$/, fnc: 'showGenshinInventory' }
            ]
        })
    }

    async showGenshinInventory(e) {
        if (!fs.existsSync('resources/html/原神背包.html')) {
            fs.mkdirSync('resources/html', { recursive: true })
            const htmlContent = await (await fetch('https://gitee.com/Tloml-Starry/resources/raw/master/resources/html/原神背包.html')).text()
            fs.writeFileSync('resources/html/原神背包.html', htmlContent)
        }

        const userUid = await MysInfo.getUid(e)
        if (!userUid) return false

        if (!await MysInfo.checkUidBing(userUid, e)) {
            await e.reply(MysInfo.tips)
            return false
        }

        const deviceFingerprint = await MysInfo.get(e, 'getFp')
        const requestHeaders = {
            'x-rpc-device_fp': deviceFingerprint?.data?.device_fp
        }

        const requestBody = await (await fetch('https://gitee.com/Tloml-Starry/resources/raw/master/resources/json/mihoyo/computeBody.json')).json()

        const computeResult = await MysInfo.get(e, 'compute', {
            body: { ...requestBody, uid: userUid },
            headers: requestHeaders
        })

        const inventoryItems = computeResult.data.overall_consume
        const categorizedInventory = this.initializeInventoryStructure()

        const itemTypeMap = await (await fetch('https://gitee.com/Tloml-Starry/resources/raw/master/resources/json/mihoyo/itemType.json')).json()

        this.categorizeItems(inventoryItems, itemTypeMap, categorizedInventory)

        const inventoryImage = await puppeteer.screenshot('原神背包', {
            tplFile: 'resources/html/原神背包.html',
            data: categorizedInventory
        })

        return e.reply(inventoryImage)
    }

    initializeInventoryStructure() {
        return {
            基础材料: [],
            采集物: [],
            角色与武器培养素材: [],
            武器突破素材: [],
            角色天赋素材: [],
            角色突破素材: [],
            首领材料: [],
            周本材料: [],
            其他: []
        }
    }

    categorizeItems(inventoryItems, itemTypeMap, categorizedInventory) {
        for (const item of inventoryItems) {
            const itemQuantity = this.calculateItemQuantity(item)
            const itemCategory = this.getItemCategory(item.name, itemTypeMap)

            if (itemCategory && categorizedInventory[itemCategory]) {
                this.addItemToCategory(categorizedInventory, itemCategory, item, itemQuantity)
            } else {
                categorizedInventory['其他'].push(this.createItemObject(item, itemQuantity))
            }
        }
    }

    calculateItemQuantity(item) {
        return item.lack_num < 0 ? Math.abs(item.lack_num) + item.num : item.num - item.lack_num
    }

    addItemToCategory(categorizedInventory, itemCategory, item, itemQuantity) {
        const itemObject = this.createItemObject(item, itemQuantity)
        if (itemCategory === '角色天赋素材' && item.name === '智识之冕') {
            categorizedInventory[itemCategory].unshift(itemObject)
        } else {
            categorizedInventory[itemCategory].push(itemObject)
        }
    }

    createItemObject(item, quantity) {
        return {
            name: item.name,
            icon: item.icon,
            number: quantity
        }
    }

    getItemCategory(itemName, itemTypeMap) {
        for (const [category, items] of Object.entries(itemTypeMap)) {
            if (items.includes(itemName)) {
                return category
            }
        }
        return null
    }
}